<template>
  <view class="withdraw-container">
	  <status-bar bgColor = "#4c9bfb"></status-bar>
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="back-btn" @click="goBack">
        <image src="/static/images/icon/backward_flat.png" class="back-icon-img"></image>
      </view>
      <view class="nav-title">申请提现</view>
    </view>
    
    <!-- 账户余额区域 -->
    <view class="balance-info">
      <view class="balance-label">账户余额：</view>
      <view class="balance-value">¥ {{accountBalance}}</view>
    </view>
    
    <!-- 提现金额输入区域 -->
    <view class="amount-input-area">
      <view class="input-box">
        <view class="input-label">自定义金额</view>
        <input 
          type="digit" 
          v-model="customAmount" 
          placeholder="请输入提现金额" 
          class="amount-input"
          @input="onCustomAmountInput"
        />
      </view>
      
      <!-- 快捷金额选择 -->
      <view class="quick-amount-grid">
        <view 
          v-for="(amount, index) in quickAmounts" 
          :key="index" 
          class="amount-item" 
          :class="{ 'amount-item-selected': selectedAmount === amount }"
          @click="selectAmount(amount)"
        >
          ¥ {{amount}}
        </view>
      </view>
      
      <!-- 提现按钮 -->
      <view 
        class="withdraw-btn" 
        :class="{ 'withdraw-btn-disabled': !canWithdraw }"
        @click="submitWithdraw"
      >
        ¥ {{selectedAmount || customAmount || 0}} 立即申请
      </view>
    </view>
    
    <!-- 提现记录区域 -->
    <view class="withdraw-records">
      <view class="record-item" v-for="(record, index) in withdrawRecords" :key="index" @click="record.status === '待审批' && showCancelConfirm(record)">
        <view class="record-info">
          <view class="record-amount">申请金额: {{record.amount}}</view>
          <view class="record-date">{{record.date}}</view>
        </view>
        <view class="record-status" :class="getStatusClass(record.status)">
          {{record.status}}
          <view class="record-reason" v-if="record.reason">{{record.reason}}</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { addApplylog, applyList, cancelApply } from '@/api/app/master/applylog';

export default {
  onLoad(options) {
    // 接收从钱包页面传递的金额参数
    if (options.amount) {
      this.accountBalance = options.amount;
    }
    // 获取提现记录
    this.getWithdrawRecordList();
  },
  data() {
    return {
      accountBalance: '0.00',
      customAmount: '',
      selectedAmount: '',
      quickAmounts: [50, 100, 200, 300, 500, 1000],
      withdrawRecords: []
    }
  },
  computed: {
    canWithdraw() {
      const amount = parseFloat(this.selectedAmount || this.customAmount || 0);
      return amount > 0 && amount <= parseFloat(this.accountBalance);
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    selectAmount(amount) {
      this.selectedAmount = amount;
      this.customAmount = '';
    },
    onCustomAmountInput() {
      this.selectedAmount = '';
      
      // 限制只能输入数字和小数点
      this.customAmount = this.customAmount.replace(/[^\d.]/g, '');
      
      // 确保只有一个小数点
      const parts = this.customAmount.split('.');
      if (parts.length > 2) {
        this.customAmount = parts[0] + '.' + parts.slice(1).join('');
      }
      
      // 限制小数点后两位
      if (parts.length === 2 && parts[1].length > 2) {
        this.customAmount = parts[0] + '.' + parts[1].substring(0, 2);
      }
      
      // 确保金额不超过账户余额
      const inputAmount = parseFloat(this.customAmount);
      const maxAmount = parseFloat(this.accountBalance);
      if (inputAmount > maxAmount) {
        this.customAmount = this.accountBalance;
      }
    },
    // 获取提现记录列表
    getWithdrawRecordList() {
      uni.showLoading({
        title: '加载中...'
      });
      applyList().then(res => {
        uni.hideLoading();
        if (res.code === 200 && res.rows) {
          this.withdrawRecords = res.rows.map(item => {
            // 根据后端返回的数据格式进行适配
            return {
              id: item.id, // 保存申请ID，用于撤销操作
              amount: item.applyAmount,
              date: item.applyTime,
              status: this.formatStatus(item.applyStatus),
              reason: item.approveremark || '',
              statusCode: item.applyStatus // 保存原始状态码
            };
          });
        }
      }).catch(err => {
        uni.hideLoading();
        console.error('获取提现记录失败:', err);
      });
    },
    
    // 格式化状态
    formatStatus(status) {
      // 根据后端返回的状态码转换为显示文本
      const statusMap = {
        1: '待审批',
        2: '通过',
        3: '驳回',
        0: '撤销'
      };
      return statusMap[status] || '未知状态';
    },
    
    // 提交提现申请
    submitWithdraw() {
      if (!this.canWithdraw) {
        return;
      }
      
      const amount = this.selectedAmount || this.customAmount;
      
      uni.showModal({
        title: '确认提现',
        content: `确定要提现 ¥${amount} 吗？`,
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: '提交中...'
            });
            
            // 调用提现接口
            addApplylog({
              applyAmount: parseFloat(amount)
            }).then(res => {
              uni.hideLoading();
              if (res.code === 200) {
                // 添加新的提现记录
                const now = new Date();
                const dateStr = now.getFullYear() + '-' + 
                  String(now.getMonth() + 1).padStart(2, '0') + '-' + 
                  String(now.getDate()).padStart(2, '0') + ' ' + 
                  String(now.getHours()).padStart(2, '0') + ':' + 
                  String(now.getMinutes()).padStart(2, '0');
                
                this.withdrawRecords.unshift({
                  amount: amount,
                  date: dateStr,
                  status: '待审批'
                });
                
                // 更新账户余额 这里先不更新，需要审批后才能更新
                // this.accountBalance = (parseFloat(this.accountBalance) - parseFloat(amount)).toFixed(2);
                
                // 重置选择
                this.selectedAmount = '';
                this.customAmount = '';
                
                uni.showToast({
                  title: '提现申请已提交',
                  icon: 'success'
                });
                this.getWithdrawRecordList();


              } else {
                uni.showToast({
                  title: res.msg || '提现申请失败',
                  icon: 'none'
                });
              }
            }).catch(err => {
              uni.hideLoading();
              uni.showToast({
                title: '提现申请失败，请稍后重试',
                icon: 'none'
              });
              console.error('提现申请失败:', err);
            });
          }
        }
      });
    },
    // 显示撤销确认弹窗
    showCancelConfirm(record) {
      uni.showModal({
        title: '撤销申请',
        content: `确定要撤销金额为 ¥${record.amount} 的提现申请吗？`,
        success: (res) => {
          if (res.confirm) {
            this.handleCancelApply(record);
          }
        }
      });
    },
    
    // 处理撤销申请
    handleCancelApply(record) {
      uni.showLoading({
        title: '处理中...'
      });
      
      // 这里需要获取申请记录的ID，假设后端返回的数据中包含id字段
      const applyId = record.id;
      
      if (!applyId) {
        uni.hideLoading();
        uni.showToast({
          title: '申请ID不存在，无法撤销',
          icon: 'none'
        });
        return;
      }
      
      cancelApply({id: applyId}).then(res => {
        uni.hideLoading();
        
        if (res.code === 200) {
          // 更新记录状态
          record.status = '撤销';
          
          // 更新账户余额（将撤销的金额加回账户余额） 这里也是需要审核才能更新余额
          // this.accountBalance = (parseFloat(this.accountBalance) + parseFloat(record.amount)).toFixed(2);
          
          uni.showToast({
            title: '申请已撤销',
            icon: 'success'
          });
          this.getWithdrawRecordList();

        } else {
          uni.showToast({
            title: res.msg || '撤销失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        uni.hideLoading();
        uni.showToast({
          title: '撤销失败，请稍后重试',
          icon: 'none'
        });
        console.error('撤销申请失败:', err);
      });
    },
    
    getStatusClass(status) {
      switch(status) {
        case '待审批':
          return 'status-pending';
        case '通过':
          return 'status-approved';
        case '撤销':
          return 'status-cancelled';
        case '驳回':
          return 'status-rejected';
        default:
          return '';
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.withdraw-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 90rpx;
  background-color: #4c9bfb;
  color: #fff;
  padding: 0 30rpx;
  position: relative;
}

.back-btn {
  position: absolute;
  left: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon-img {
  width: 40rpx;
  height: 40rpx;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
}

/* 账户余额区域 */
.balance-info {
  background-color: #4c9bfb;
  padding: 20rpx 30rpx;
  color: #fff;
  display: flex;
  align-items: center;
}

.balance-label {
  font-size: 28rpx;
}

.balance-value {
  font-size: 32rpx;
  font-weight: bold;
}

/* 提现金额输入区域 */
.amount-input-area {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.input-box {
  margin-bottom: 30rpx;
}

.input-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.amount-input {
  width: 100%;
  height: 80rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 32rpx;
  box-sizing: border-box;
}

/* 快捷金额选择 */
.quick-amount-grid {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10rpx 30rpx;
}

.amount-item {
  width: calc(33.33% - 20rpx);
  height: 80rpx;
  margin: 10rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #333;
  box-sizing: border-box;
}

.amount-item-selected {
  border-color: #e74c3c;
  color: #e74c3c;
}

/* 提现按钮 */
.withdraw-btn {
  width: 100%;
  height: 90rpx;
  background-color: #e74c3c;
  color: #fff;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: bold;
}

.withdraw-btn-disabled {
  background-color: #ccc;
}

/* 提现记录区域 */
.withdraw-records {
  background-color: #fff;
  padding: 0 30rpx;
}

.record-item {
  display: flex;
  justify-content: space-between;
  padding: 30rpx 0;
  border-bottom: 1px solid #eee;
}

.record-item:last-child {
  border-bottom: none;
}

.record-info {
  display: flex;
  flex-direction: column;
}

.record-amount {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.record-date {
  font-size: 24rpx;
  color: #999;
}

.record-status {
  font-size: 28rpx;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.status-pending {
  color: #f39c12;
}

.status-approved {
  color: #2ecc71;
}

.status-cancelled {
  color: #7f8c8d;
}

.status-rejected {
  color: #e74c3c;
}

.record-reason {
  font-size: 24rpx;
  color: #999;
  margin-top: 5rpx;
}
</style>